package com.iclient.web.controller;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.iclient.web.BaseController;
import com.plugins.http.MyLogin;

@Controller
public class SinaAccountController extends BaseController{
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@ResponseBody
	@RequestMapping(value="/sina/account.json")
	public ModelMap list(){
		Map<String, String> resultMap = MyLogin.getLoginCode();
		if(null != resultMap){
			redisTemplate.opsForValue().set("sina:account:login:1", JSONObject.toJSONString(resultMap));
			redisTemplate.expire("sina:account:login:1", 1, TimeUnit.MINUTES);
			return buildResponseMap(true, resultMap);
		}
		return buildResponseMap(false, "获取登录验证码异常");
	}

	@ResponseBody
	@RequestMapping(value="/sina/login.json")
	public ModelMap doLogin(String id, String code){
		Object obj = redisTemplate.opsForValue().get("sina:account:login:1");
		if(null == obj){
			return buildResponseMap(false, "登陆参数已过期");
		}
		redisTemplate.delete("sina:account:login:1");
		Map<String, String> param = JSON.parseObject(obj.toString(), new TypeReference<TreeMap<String, String>>(){});
		param.put("code", code);
		String cookie = MyLogin.doLogin(param);
		if(StringUtils.isNotBlank(cookie)){
			redisTemplate.opsForValue().set("sina.account.cookie:1", cookie);
			redisTemplate.expire("sina.account.cookie:1", 15, TimeUnit.DAYS);
			return buildResponseMap(true, "登陆成功", cookie);
		}
		return buildResponseMap(false, "登陆失败", "");
	}
}
